﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace OnlineBattlemat
{
	public partial class TokenControl : UserControl
	{
		#region Private Fields
		// Reference to the main page
		private Page m_Page;
		private Token m_Token;

		private double m_dragOffsetX;
		private double m_dragOffsetY;

		private bool m_IsDragging;
		#endregion

		#region Public Properties
		/// <summary>
		/// The token displayed by this control
		/// </summary>
		public Token Token
		{
			get { return m_Token; }
			set
			{
				m_Token = value;
				UpdateContent();
			}
		}
		#endregion

		#region Constructors
		public TokenControl()
		{
			InitializeComponent();
			SetupEventHandlers();

			m_Page = Page.GetCurrentPage();
		}

		public TokenControl(Token token)
		{
			InitializeComponent();
			SetupEventHandlers();

			Token = token;

			m_Page = Page.GetCurrentPage();
		}
		#endregion

		#region Private Methods
		private void SetupEventHandlers()
		{
			this.MouseLeftButtonDown += new MouseButtonEventHandler(TokenControl_MouseLeftButtonDown);
			this.MouseMove += new MouseEventHandler(TokenControl_MouseMove);
			this.MouseLeftButtonUp += new MouseButtonEventHandler(TokenControl_MouseLeftButtonUp);
		}

		private void UpdateContent()
		{
			x_TokenImage.Source = m_Token.Image;
			
			x_TokenName.Text = m_Token.Name;
		}
		#endregion

		#region Event Handlers

        private void TokenControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			if (m_Page.CurrentTool == OnlineBattlemat.Page.Tools.Pointer)
			{
				m_dragOffsetX = e.GetPosition(this).X;
				m_dragOffsetY = e.GetPosition(this).Y;
				this.CaptureMouse();
				m_IsDragging = true;
                e.Handled = true;
			}
			else if (m_Page.CurrentTool == OnlineBattlemat.Page.Tools.Eraser)
			{
                m_Page.x_InkPresenterElement.Children.Remove(this);
                e.Handled = true;
			}
		}

		private void TokenControl_MouseMove(object sender, MouseEventArgs e)
		{
			if (m_IsDragging)
			{
				this.SetValue(Canvas.LeftProperty, e.GetPosition(m_Page.x_MainCanvas).X - m_dragOffsetX);
				this.SetValue(Canvas.TopProperty, e.GetPosition(m_Page.x_MainCanvas).Y - m_dragOffsetY);
			}
		}

		private void TokenControl_MouseLeftButtonUp(object sender, MouseEventArgs e)
		{
			this.ReleaseMouseCapture();
			m_IsDragging = false;
		}
		#endregion
	}
}
